extends Node

# 场景管理器 - 处理场景切换和传送门位置管理

# 传送门位置映射表 - 动态注册
# 格式: {"场景路径": {"传送门ID": Vector2位置}}
var portal_positions = {}

# 当前传送的目标传送门ID
var target_portal_id: String = ""
# 刚刚传送到的传送门ID，用于避免循环传送
var just_teleported_to_portal: String = ""

# 玩家管理器引用
@onready var player_manager = get_node("/root/PlayerManager")

func _ready():
	# 设置为自动加载单例
	process_mode = Node.PROCESS_MODE_ALWAYS
	
	# 监听场景切换
	get_tree().tree_changed.connect(_on_scene_changed)

# 通过传送门传送到目标场景
func teleport_to_scene(target_scene: String, portal_id: String):
	target_portal_id = portal_id
	just_teleported_to_portal = portal_id  # 记录传送到的传送门ID
	
	# 保存玩家数据
	if player_manager != null:
		player_manager.save_player_data()
	
	# 切换场景
	get_tree().change_scene_to_file(target_scene)
	
	# 等待场景切换完成后设置玩家位置
	await get_tree().tree_changed
	await get_tree().process_frame
	_on_scene_loaded()

# 注册传送门位置（保留用于调试信息）
func set_portal_position(scene_path: String, portal_id: String, position: Vector2):
	if not portal_positions.has(scene_path):
		portal_positions[scene_path] = {}
	portal_positions[scene_path][portal_id] = position
	print("传送门注册: ", portal_id, " 位置: ", position, " 场景: ", scene_path)

# 场景切换监听
func _on_scene_changed():
	# 移除自动调用_on_scene_loaded，避免重复生成玩家
	# 现在由teleport_to_scene函数直接处理
	pass

# 场景加载完成后调用，设置玩家位置
func _on_scene_loaded():
	if target_portal_id.is_empty():
		# 没有目标传送门，使用默认位置生成玩家
		if player_manager != null:
			player_manager.spawn_player_in_current_scene()
		return
	
	# 等待一帧确保场景完全加载
	await get_tree().process_frame
	
	var current_scene = get_tree().current_scene
	
	# 直接在当前场景中查找目标传送门
	var target_portal = find_portal_by_id(current_scene, target_portal_id)
	if target_portal != null:
		# 使用传送门的实际位置生成玩家
		var portal_position = target_portal.global_position
		if player_manager != null:
			player_manager.spawn_player_at_position(portal_position)
		print("玩家传送到传送门位置: ", portal_position)
	else:
		print("警告：未找到传送门 ", target_portal_id, " 在当前场景")
		# 使用默认位置生成玩家
		if player_manager != null:
			player_manager.spawn_player_in_current_scene()
	
	# 清除目标传送门ID
	target_portal_id = ""

# 获取当前玩家节点
func get_current_player() -> Node:
	if player_manager != null:
		return player_manager.get_current_player()
	return null

# 递归查找指定ID的传送门节点
func find_portal_by_id(node: Node, portal_id: String) -> Node:
	# 检查当前节点是否是传送门且ID匹配
	if node.has_method("teleport_player") and "portal_id" in node:
		if node.portal_id == portal_id:
			return node
	
	# 递归查找子节点
	for child in node.get_children():
		var result = find_portal_by_id(child, portal_id)
		if result != null:
			return result
	
	return null
